//
//  XS_SearchTongyongVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/22.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class XS_SearchTongyongVC: XS_BaseVC {
    enum ListType {
        case curriculum // 课程
        case recruitment // 招聘
        case news // 资讯
    }

    var type: ListType!
    var searchWhere: String!
    private lazy var page = 0
    private lazy var dataPS = PublishSubject<[XS_SearchVC.SearchType]>()
    private lazy var data: [XS_SearchVC.SearchType] = []
    private lazy var footer = MJRefreshBackNormalFooter()
    lazy var table = UITableView(frame: .zero, style: .grouped)
    
    
    override func upView() {
        
        table.contentInsetAdjustmentBehavior = .never
        table.showsVerticalScrollIndicator = false
//        table.bounces = false
        table.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        table.separatorStyle = .none
        table.rowHeight = .scale*104
        table.sectionHeaderHeight = 0
        table.sectionFooterHeight = 0
        table.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.register(XS_SearchCurriculum.self, forCellReuseIdentifier: "课程")
        table.register(XS_SearchRecruitment.self, forCellReuseIdentifier: "就业")
        table.register(XS_SearchNews.self, forCellReuseIdentifier: "资讯")
        view.addSubview(table)
        table.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        table.rx.setDelegate(self)
            .disposed(by: disposeBag)
        
        let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, XS_SearchVC.SearchType>>(configureCell: { ds, tv, ip, it in
            switch it {
            case .curriculum(_):
                let cell = tv.dequeueReusableCell(withIdentifier: "课程", for: ip) as! XS_SearchCurriculum
                cell.modelPS.onNext(it)
                return cell
            case .recruitment(_):
                let cell = tv.dequeueReusableCell(withIdentifier: "就业", for: ip) as! XS_SearchRecruitment
                cell.modelPS.onNext(it)
                return cell
            case .news(_):
                let cell = tv.dequeueReusableCell(withIdentifier: "资讯", for: ip) as! XS_SearchNews
                cell.modelPS.onNext(it)
                return cell
//            default: return UITableViewCell()
            }
        })
        
        table.rx.modelSelected(XS_SearchVC.SearchType.self)
            .asDriver()
            .drive(onNext: { [weak self] type in
                guard let `self` = self else { return }
                switch type {
                case let .curriculum(item):
                    let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                    vc.id = "\(item.id)"
                    XS_NVC.shared.pushViewController(vc, animated: true)
                case let .recruitment(item):
                    XS_NetWork.requestJson("/recruitment/queryRecruitmentById", parameters: ["id":item.id])
                        .mapModel(type: XS_queryRecruitmentListM.self)
                        .subscribe(onNext: { model, resp in
                            guard resp.success, let model = model else { return }
                            let vc = XS_ZhaopinDetailVC()
                            vc.model = model
                            XS_NVC.shared.pushViewController(vc, animated: true)
                        }).disposed(by: self.disposeBag)
                case let .news(item):
//                    let vc = XS_WebPageVC("/Home?id=\(item.id)")
                    let vc = XS_WebPageVC(item.shareUrl)
                    vc.isShare = true
                    XS_NVC.shared.pushViewController(vc, animated: true)
                }
            }).disposed(by: disposeBag)
        
        dataPS.asDriver(onErrorJustReturn: [])
            .flatMapLatest { Driver.just([SectionModel<String, XS_SearchVC.SearchType>(model: "", items: $0)]) }
            .drive(table.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        table.mj_footer = footer
        footer.rx.refresh
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.loadMore()
            }).disposed(by: disposeBag)
        loadMore()
    }
    
    func loadMore() {
        if page == 0 {
            data.removeAll()
        }
        
        let param: [String:Any] = [
            "pageNo":page+1,
            "searchWhere": searchWhere ?? ""
        ]
        
        switch type {
        case .curriculum:
            XS_NetWork.requestJson("/search/searchCurriculum", parameters: param)
                .mapModel(type: XS_ListM<XS_searchQueryCurriculumM>.self)
                .subscribe(onNext: { [weak self] model, resp in
                    guard let `self` = self, resp.success, let model = model else { return }
                    self.page = model.current
                    self.data += model.records.compactMap({ .curriculum($0) })
                    self.dataPS.onNext(self.data)
                    if model.current < model.pages {
                        self.footer.endRefreshing()
                    } else {
                        self.footer.endRefreshingWithNoMoreData()
                    }
                }).disposed(by: disposeBag)
        case .recruitment:
            XS_NetWork.requestJson("/search/searchRecruitment", parameters: param)
                .mapModel(type: XS_ListM<XS_searchQueryRecruitmentM>.self)
                .subscribe(onNext: { [weak self] model, resp in
                    guard let `self` = self, resp.success, let model = model else { return }
                    self.page = model.current
                    self.data += model.records.compactMap({ .recruitment($0) })
                    self.dataPS.onNext(self.data)
                    if model.current < model.pages {
                        self.footer.endRefreshing()
                    } else {
                        self.footer.endRefreshingWithNoMoreData()
                    }
                }).disposed(by: disposeBag)
        case .news:
            XS_NetWork.requestJson("/search/searchNews", parameters: param)
                .mapModel(type: XS_ListM<XS_searchQueryNewsM>.self)
                .subscribe(onNext: { [weak self] model, resp in
                    guard let `self` = self, resp.success, let model = model else { return }
                    self.page = model.current
                    self.data += model.records.compactMap({ .news($0) })
                    self.dataPS.onNext(self.data)
                    if model.current < model.pages {
                        self.footer.endRefreshing()
                    } else {
                        self.footer.endRefreshingWithNoMoreData()
                    }
                }).disposed(by: disposeBag)
        case .none:
            break
        }
        
        
        
        
    }
}

extension XS_SearchTongyongVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if type == .recruitment {
            return .scale*116
        }
        return .scale*104
    }
}
